<script setup lang="ts">
import { useAppStore } from "@/store/modules/app";
import { useUserStore } from "@/store/modules/user";
import { usePermissionStoreHook } from "@/store/modules/permission";
import {
  useRouter,
  useRoute,
} from "vue-router";
import { reqUserinfo, } from "@/api/business/user";
import { reqMultiRoles } from "@/api/business/menu";
const appStore = useAppStore();
const userStore = useUserStore();
const router = useRouter();
const permissionStore = usePermissionStoreHook();

onMounted(() => {
  console.log('app mounted')
  // 如果地址栏包含 user 、password 、 tokens，代表是综合管理系统跳转过来的，需要走默认登录流程,且不是跟登录的为同一个用户

  if (getUrlKey("user") && getUrlKey("password") && getUrlKey("tokens")) {
    let loginForm = {
      loginName: getUrlKey("user"),
      password: getUrlKey("password")
    }
    localStorage.setItem("loginForm", JSON.stringify(loginForm))

    window.location.href = `${location.origin}/#/login`;

  }
  if (localStorage.getItem("loginForm")) {
    userStore.login(JSON.parse(localStorage.getItem("loginForm"))).then(async (res) => {
      const rolesList = await userStore.getUserInfo();
      const accessRoutes = await permissionStore.generateRoutes(rolesList);
      accessRoutes.forEach((route) => {
        router.addRoute(route);
      });

      localStorage.removeItem("loginForm");
      router.push('/')
    })
  }


});



const getUrlKey = (name: string) => {
  return (
    decodeURIComponent(
      (new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
        location.href
      ) || [, ""])[1].replace(/\+/g, "%20")
    ) || null
  );
}
</script>

<template>
  <el-config-provider :locale="appStore.locale" :size="appStore.size">
    <router-view />
  </el-config-provider>
</template>
